﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using SCGILite.NetLib;
using SCGILite.Helper;

namespace SCGITest.PageTemplate
{
    class PageFactory
    {
        public void Init()
        {
            Thread t = new Thread(OnTime);
            t.IsBackground = true;
            t.Start();
        }
        #region OnSCGIBody
        public void OnSCGIBody(DemoSCGISession se)
        {
            ITemplatePage page = null;
            if (se.Request.REQUEST_URI.Contains("Async"))
            {
                page = new AsyncPage(se);
            }
            else
            {
                page = new SyncPage(se);
            }
            if (page.AsyncEnd)
                page.End();
            else
            {
                lock (lst)
                {
                    se.isAsync = true;
                    lst.Add(page);
                }
            }
        }
        #endregion

        #region OnErr
        public void OnErr(DemoSCGISession se, Exception e)
        {
            ErrPage errPage = new ErrPage(e);
            errPage.se = se;
            try
            {
                errPage.End();
            }
            catch
            {
            }
            se.EndResponse();
        }
        #endregion

        #region OnTime
        List<ITemplatePage> lst = new List<ITemplatePage>();
        void OnTime()
        {
            while (true)
            {
                Thread.Sleep(1000);
                while (true)
                {
                    ITemplatePage[] a = null;
                    lock (lst)
                    {
                        a = lst.ToArray();
                    }
                    for (int i = a.Length - 1; i >= 0; i--)
                    {
                        ITemplatePage aa = a[i];
                        if (aa.AsyncEnd)
                        {
                            lock (lst)
                            {
                                lst.RemoveAt(i);
                            }
                            try
                            {
                                aa.End();
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
        }
        #endregion
    }
}
